import { Global, Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { ConfigService } from "@nestjs/config";
import { RedisModule } from "@nestjs-modules/ioredis";
import { BullModule } from "@nestjs/bull";
import { SharedService } from "./shared.service";
import { APP_GUARD, APP_INTERCEPTOR } from "@nestjs/core";
import { ResponseTransformInterceptor } from "src/common/interceptors/response-transform.interceptor";
import { JwtAuthGuard } from "src/common/guards/jwt-auth.guard";
import { LogModule } from "src/modules/monitor/log/log.module";

// @Global 装饰器使模块成为全局作用域,任何地方都可以使用
@Global()
@Module({
  imports: [
    /** 连接mysql数据库 */
    TypeOrmModule.forRootAsync({
      useFactory: (configService: ConfigService) => ({
        autoLoadEntities: true,
        type: configService.get<any>("database.type"),
        host: configService.get<string>("database.host"),
        port: configService.get<number>("database.port"),
        username: configService.get<string>("database.username"),
        password: configService.get<string>("database.password"),
        database: configService.get<string>("database.database"),
        autoLoadModels: configService.get<boolean>("database.autoLoadModels"),
        synchronize: configService.get<boolean>("database.synchronize"),
        logging: configService.get("database.logging"),
      }),
      inject: [ConfigService],
    }),
    /* 连接redis */
    RedisModule.forRootAsync({
      useFactory: (configService: ConfigService) => configService.get<any>("redis"),
      inject: [ConfigService],
    }),
    /* 启用队列 */
    BullModule.forRootAsync({
      useFactory: async (configService: ConfigService) => ({
        redis: {
          host: configService.get<string>("bullRedis.host"),
          port: configService.get<number>("bullRedis.port"),
        },
      }),
      inject: [ConfigService],
    }),
    LogModule,
  ],
  controllers: [],
  providers: [
    SharedService,

    // jwt守卫
    {
      provide: APP_GUARD,
      useClass: JwtAuthGuard,
    },
    // 全局返回值拦截器
    {
      provide: APP_INTERCEPTOR,
      useClass: ResponseTransformInterceptor,
    },
  ],
  exports: [SharedService],
})
export class SharedModule {}
